package com.team.teamuserservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team.teamuserservice.entity.dto.UserDto;
import com.team.teamuserservice.entity.po.BizUserInfo;
import com.team.teamuserservice.entity.vo.UserVo;
import com.team.teamuserservice.mapper.BizUserInfoMapper;
import com.team.teamuserservice.service.IBizUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team.teamuserservice.uitls.AliyunOSSOperator;
import com.team.teamuserservice.uitls.PageResult;
import com.team.teamuserservice.uitls.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author cxs
 * @since 2025-07-09
 */
@Service
@RequiredArgsConstructor
public class BizUserInfoServiceImpl extends ServiceImpl<BizUserInfoMapper, BizUserInfo> implements IBizUserInfoService {

    private final AliyunOSSOperator aliyunOSSOperator;


    /**
     * 上传头像并保存到数据库
     * @param file
     * @param id
     */
    @Override
    public Result upLoad(MultipartFile file, Long id) throws Exception {
        //判空
        if (file == null || file.isEmpty()){
            return Result.error("你在传nm呢, 传了个空值进来");
        }

        //先上传到aliyunOSS
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());

        //把url保存到相应的用户
        boolean success = lambdaUpdate()
                .set(BizUserInfo::getAvatarUrl, url)
                .set(BizUserInfo::getUpdateTime, LocalDateTime.now())
                .eq(BizUserInfo::getId, id)
                .update();

        if (success){
            return Result.success(url);
        }
        return Result.error("完蛋了,图片上传失败");
    }

    /**
     * vue端的分页查询
     * @param userDto
     * @return
     */
    @Override
    public Result pageList(UserDto userDto) {

        Page<BizUserInfo> page = new Page<>(userDto.getPageNum(), userDto.getPageSize());

        lambdaQuery()
                .like(userDto.getUserName() != null && !userDto.getUserName().isEmpty(), BizUserInfo::getUserName, userDto.getUserName())
                .eq(userDto.getPhone() != null && !userDto.getPhone().isEmpty(), BizUserInfo::getPhone, userDto.getPhone())
                .between(userDto.getCreateTime() != null && userDto.getEndTime() != null, BizUserInfo::getCreateTime, userDto.getCreateTime(), userDto.getEndTime())
                .page(page);

        PageResult<UserVo> pageResult = new PageResult<>(page.getTotal(), BeanUtil.copyToList(page.getRecords(), UserVo.class));


        return Result.success(pageResult);

    }
}
